package woa.stack;

import woa.linkedlist.ListNode;

/**
 * 链式栈
 * 用链表实现，无长度上限
 *
 * @author wangpeng
 * @date 2021/11/9
 */
public class LinkedStack implements WoaStack {

    private ListNode head = null;
    private ListNode tail = null;
    private int length = Integer.MAX_VALUE;
    private int count;

    @Override
    public boolean push(int item) {
        if (count == length) {
            return false;
        }
        ListNode listNode = new ListNode(item);
        if (head == null) {
            head = listNode;
            tail = listNode;
        } else {
            tail.next = listNode;
            tail = tail.next;
        }
        count++;
        return true;
    }

    @Override
    public int pop() {
        if (tail == null) {
            return -1;
        }
        ListNode cur = head;
        for (int i = 0; i < count - 1; i++) {
            cur = head.next;
        }
        cur.next = null;
        count--;
        return tail.val;
    }
}
